package njClass.net{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	import njClass.base.memory;
	
	public class LoaderPlus extends EventDispatcher{
		private var url:String;
		private var data:ByteArray;
		private var stream:URLStream;
		private var CallBackFunction:Function;
		
		public function LoaderPlus(url:String,CallBackFunction:Function=null,autoLoad:Boolean=true){
		this.CallBackFunction=CallBackFunction;
			this.url=url;
			if(autoLoad){
				start();
			}
		}
		
		public function get Data():ByteArray{
			return data;
		}
		
		public function updataURL(url:String,autoLoad:Boolean=true):void{
			close();
			this.url = url;
			if(autoLoad){
				start();
			}
		}
		
		//加载
		public function start():void{
			data = new ByteArray;
			stream = new URLStream;
			stream.load(new URLRequest(url));
			stream.addEventListener(Event.COMPLETE,completeFun);
			stream.addEventListener(ProgressEvent.PROGRESS,progressFun);
		}
		
		//加载中
		private function progressFun(e:ProgressEvent):void{
			if(stream.bytesAvailable == 0){
				return;
			}
			updata();
			dispatchEvent(new ProgressEvent("Loading",false,false,e.bytesLoaded,e.bytesTotal));
		}
		
		//加载完成
		private function completeFun(e:Event):void{
			stream.removeEventListener(Event.COMPLETE,completeFun);
			stream.removeEventListener(ProgressEvent.PROGRESS,progressFun);
			updata();
			if(isLoad){
				stream.close();
			}
			if(CallBackFunction==null){
				dispatchEvent(new Event("Loaded"));
			}else{
				var loader:Loader=new Loader();
				loader.loadBytes(data);
				CallBackFunction(loader);
			}
		}
		
		//更新数据
		public function updata():void{
			if(isLoad) stream.readBytes(data,data.length);
		}
		
		//清除数据
		public function close():void{
			if(isLoad) stream.close();
			stream = null;
			data = null;
			memory.doGC();
		}
		
		//获取是否有数据在加载
		public function get isLoad():Boolean{
			if(stream == null) return false;
			return stream.connected;
		}
	}
}